package com.bridgeintelligent.tag.webserver.dim.mgmt.api;

/**
 * Created by JackCheung on 2018/10/2 下午1:40.
 */
public class IdWorker {

    private final static long workerId = 2;
    private final static long twepoch = 1288834974657L;
    private final static long workerIdBits = 4L;
    private final static long sequenceBits = 10L;
    private final static long workerIdShift = sequenceBits;
    private final static long timestampLeftShift = sequenceBits + workerIdBits;
    private static long lastTimestamp = -1L;

    public static synchronized String nextId() {
        long timestamp = timeGen();
        long sequence;
        if (lastTimestamp == timestamp) {
            sequence = 0L;
            timestamp = tilNextMillis(lastTimestamp);
        } else {
            sequence = 0;
        }
        lastTimestamp = timestamp;
        long nextId = ((timestamp - twepoch << timestampLeftShift)) | (workerId << workerIdShift) | (sequence);
        return String.valueOf(nextId);
    }

    private static long tilNextMillis(final long lastTimestamp) {
        long timestamp = timeGen();
        while (timestamp <= lastTimestamp) {
            timestamp = timeGen();
        }
        return timestamp;
    }

    private static long timeGen() {
        return System.currentTimeMillis();
    }
}
